const db = require('../config/db');

/**
 * 获取热点推荐店铺列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getHotRecommends = async (req, res) => {
    try {
        console.log('[API] 获取热点推荐店铺列表');
        
        // 检查hot_stores表是否存在，如果不存在则创建
        await ensureHotStoresTableExists();
        
        // 从数据库获取热点推荐店铺
        const [rows] = await db.execute(`
            SELECT 
                hs.id as recommend_id,
                s.id,
                s.name,
                s.type,
                s.logo,
                s.cover_image,
                s.description,
                s.address,
                s.rating,
                s.open_time,
                s.close_time,
                s.contact_phone as phone
            FROM 
                hot_stores hs
            JOIN 
                stores s ON hs.store_id = s.id
            ORDER BY 
                hs.sort_order ASC
            LIMIT 10
        `);
        
        console.log(`[API] 热点推荐店铺列表获取成功，共 ${rows.length} 条记录`);
        
        // 检查是否有记录
        if (rows.length === 0) {
            // 如果没有记录，插入示例数据
            await insertSampleHotStores();
            
            // 重新获取数据
            const [newRows] = await db.execute(`
                SELECT 
                    hs.id as recommend_id,
                    s.id,
                    s.name,
                    s.type,
                    s.logo,
                    s.cover_image,
                    s.description,
                    s.address,
                    s.rating,
                    s.open_time,
                    s.close_time,
                    s.contact_phone as phone
                FROM 
                    hot_stores hs
                JOIN 
                    stores s ON hs.store_id = s.id
                ORDER BY 
                    hs.sort_order ASC
                LIMIT 10
            `);
            
            console.log(`[API] 已插入示例数据，现有 ${newRows.length} 条记录`);
            return res.json(newRows);
        }
        
        res.json(rows);
    } catch (error) {
        console.error('[API] 获取热点推荐店铺列表失败:', error);
        res.status(500).json({ message: '获取热点推荐店铺列表失败' });
    }
};

/**
 * 确保hot_stores表存在
 */
const ensureHotStoresTableExists = async () => {
    try {
        // 检查表是否存在
        const [tables] = await db.execute(`
            SELECT TABLE_NAME 
            FROM information_schema.TABLES 
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'hot_stores'
        `, [process.env.DB_NAME || 'bangninsheng']);
        
        // 如果表不存在，创建它
        if (tables.length === 0) {
            console.log('[API] hot_stores表不存在，正在创建...');
            await db.execute(`
                CREATE TABLE IF NOT EXISTS hot_stores (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    store_id INT NOT NULL COMMENT '店铺ID',
                    sort_order INT DEFAULT 0 COMMENT '排序序号',
                    status INT DEFAULT 1 COMMENT '状态 (1: 正常, 0: 禁用)',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    CONSTRAINT hot_stores_ibfk_1 FOREIGN KEY (store_id) REFERENCES stores (id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='热点推荐店铺表'
            `);
            console.log('[API] hot_stores表创建成功');
        }
    } catch (error) {
        console.error('[API] 检查/创建hot_stores表失败:', error);
        throw error;
    }
};

/**
 * 插入示例热点推荐店铺数据
 * 这个函数会先检查是否有足够的店铺记录，如果没有，会先创建示例店铺
 */
const insertSampleHotStores = async () => {
    try {
        // 检查是否有足够的店铺记录
        const [storeRows] = await db.execute('SELECT id FROM stores LIMIT 5');
        
        // 如果店铺数量不足，创建示例店铺
        if (storeRows.length < 5) {
            console.log('[API] 店铺数量不足，创建示例店铺');
            await createSampleStores();
            
            // 重新获取店铺ID
            const [newStoreRows] = await db.execute('SELECT id FROM stores LIMIT 5');
            storeRows.push(...newStoreRows);
        }
        
        // 清空热点推荐表
        await db.execute('DELETE FROM hot_stores');
        
        // 插入热点推荐记录
        for (let i = 0; i < storeRows.length; i++) {
            await db.execute(
                'INSERT INTO hot_stores (store_id, sort_order) VALUES (?, ?)',
                [storeRows[i].id, i + 1]
            );
        }
        
        console.log('[API] 示例热点推荐数据插入成功');
    } catch (error) {
        console.error('[API] 插入示例热点推荐数据失败:', error);
        throw error;
    }
};

/**
 * 创建示例店铺数据
 */
const createSampleStores = async () => {
    try {
        // 示例店铺数据
        const sampleStores = [
            {
                name: '农家乐餐厅',
                type: '美食',
                description: '提供地道农家菜，环境优美',
                address: '某某县某某镇某某村',
                open_time: '09:00:00',
                close_time: '21:00:00',
                phone: '13800138000',
                rating: 4.8
            },
            {
                name: '乡村小超市',
                type: '购物',
                description: '经营各类生活用品和特色农产品',
                address: '某某县某某镇某某村',
                open_time: '08:00:00',
                close_time: '22:00:00',
                phone: '13900139000',
                rating: 4.5
            },
            {
                name: '农家客栈',
                type: '住宿',
                description: '提供舒适住宿，体验乡村生活',
                address: '某某县某某镇某某村',
                open_time: '00:00:00',
                close_time: '23:59:59',
                phone: '13700137000',
                rating: 4.7
            },
            {
                name: '乡村修理铺',
                type: '维修',
                description: '提供各类农具、电器维修服务',
                address: '某某县某某镇某某村',
                open_time: '08:30:00',
                close_time: '18:00:00',
                phone: '13600136000',
                rating: 4.6
            },
            {
                name: '特色农产品店',
                type: '农产品',
                description: '销售当地特色农产品，绿色健康',
                address: '某某县某某镇某某村',
                open_time: '09:00:00',
                close_time: '20:00:00',
                phone: '13500135000',
                rating: 4.9
            }
        ];
        
        // 首先检查是否有用户记录，如果没有，创建一个示例用户
        const [userRows] = await db.execute('SELECT id FROM users WHERE role = "store" LIMIT 1');
        let ownerId;
        
        if (userRows.length === 0) {
            const [userResult] = await db.execute(
                'INSERT INTO users (phone, name, role) VALUES (?, ?, ?)',
                ['13888888888', '示例商家', 'store']
            );
            ownerId = userResult.insertId;
        } else {
            ownerId = userRows[0].id;
        }
        
        // 插入示例店铺
        for (const store of sampleStores) {
            await db.execute(
                `INSERT INTO stores (
                    owner_id, name, type, description, address, 
                    open_time, close_time, contact_phone, rating, is_approved
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [
                    ownerId,
                    store.name,
                    store.type,
                    store.description,
                    store.address,
                    store.open_time,
                    store.close_time,
                    store.phone,
                    store.rating,
                    1 // 已审核
                ]
            );
        }
        
        console.log('[API] 示例店铺数据创建成功');
    } catch (error) {
        console.error('[API] 创建示例店铺数据失败:', error);
        throw error;
    }
};

/**
 * 管理员获取热点推荐列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getHotRecommendsAdmin = async (req, res) => {
    try {
        console.log('[API] 管理员获取热点推荐列表');
        
        // 确保表存在
        await ensureHotStoresTableExists();
        
        // 从数据库获取热点推荐列表，包含店铺信息
        const [rows] = await db.execute(`
            SELECT 
                hs.id,
                hs.store_id,
                hs.sort_order,
                hs.status,
                s.name as store_name,
                s.cover_image as store_image,
                s.type as store_type,
                s.description
            FROM 
                hot_stores hs
            JOIN 
                stores s ON hs.store_id = s.id
            ORDER BY 
                hs.sort_order ASC
        `);
        
        console.log(`[API] 热点推荐列表获取成功，共 ${rows.length} 条记录`);
        
        // 如果没有记录，尝试插入示例数据
        if (rows.length === 0) {
            await insertSampleHotStores();
            
            // 重新获取数据
            const [newRows] = await db.execute(`
                SELECT 
                    hs.id,
                    hs.store_id,
                    hs.sort_order,
                    hs.status,
                    s.name as store_name,
                    s.cover_image as store_image,
                    s.type as store_type,
                    s.description
                FROM 
                    hot_stores hs
                JOIN 
                    stores s ON hs.store_id = s.id
                ORDER BY 
                    hs.sort_order ASC
            `);
            
            console.log(`[API] 已插入示例数据，现有 ${newRows.length} 条记录`);
            return res.json(newRows);
        }
        
        res.json(rows);
    } catch (error) {
        console.error('[API] 获取热点推荐列表失败:', error);
        res.status(500).json({ message: '获取热点推荐列表失败' });
    }
};

/**
 * 添加热点推荐
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const addHotRecommend = async (req, res) => {
    try {
        console.log('[API] 添加热点推荐');
        
        // 获取请求数据
        const { store_id, sort_order = 0, status = 1 } = req.body;
        
        // 验证必填字段
        if (!store_id) {
            return res.status(400).json({ message: '店铺ID是必填项' });
        }
        
        // 检查店铺是否存在
        const [storeRows] = await db.execute('SELECT id FROM stores WHERE id = ?', [store_id]);
        if (storeRows.length === 0) {
            return res.status(404).json({ message: '店铺不存在' });
        }
        
        // 检查是否已经添加过该店铺
        const [existingRows] = await db.execute('SELECT id FROM hot_stores WHERE store_id = ?', [store_id]);
        if (existingRows.length > 0) {
            return res.status(400).json({ message: '该店铺已经在热点推荐中' });
        }
        
        // 插入数据
        const [result] = await db.execute(
            'INSERT INTO hot_stores (store_id, sort_order, status) VALUES (?, ?, ?)',
            [store_id, sort_order, status]
        );
        
        console.log('[API] 热点推荐添加成功:', result.insertId);
        res.status(201).json({ id: result.insertId, message: '添加成功' });
    } catch (error) {
        console.error('[API] 添加热点推荐失败:', error);
        res.status(500).json({ message: '添加热点推荐失败' });
    }
};

/**
 * 更新热点推荐
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const updateHotRecommend = async (req, res) => {
    try {
        const { id } = req.params;
        const { store_id, sort_order, status } = req.body;
        
        console.log(`[API] 更新热点推荐 ID: ${id}`);
        
        // 验证必填字段
        if (!store_id) {
            return res.status(400).json({ message: '店铺ID是必填项' });
        }
        
        // 检查店铺是否存在
        const [storeRows] = await db.execute('SELECT id FROM stores WHERE id = ?', [store_id]);
        if (storeRows.length === 0) {
            return res.status(404).json({ message: '店铺不存在' });
        }
        
        // 检查热点推荐是否存在
        const [recommendRows] = await db.execute('SELECT id FROM hot_stores WHERE id = ?', [id]);
        if (recommendRows.length === 0) {
            return res.status(404).json({ message: '热点推荐不存在' });
        }
        
        // 检查是否已经添加过该店铺（排除当前记录）
        const [existingRows] = await db.execute(
            'SELECT id FROM hot_stores WHERE store_id = ? AND id != ?',
            [store_id, id]
        );
        if (existingRows.length > 0) {
            return res.status(400).json({ message: '该店铺已经在热点推荐中' });
        }
        
        // 更新数据
        await db.execute(
            'UPDATE hot_stores SET store_id = ?, sort_order = ?, status = ? WHERE id = ?',
            [store_id, sort_order, status, id]
        );
        
        console.log(`[API] 热点推荐更新成功 ID: ${id}`);
        res.json({ message: '更新成功' });
    } catch (error) {
        console.error('[API] 更新热点推荐失败:', error);
        res.status(500).json({ message: '更新热点推荐失败' });
    }
};

/**
 * 删除热点推荐
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const deleteHotRecommend = async (req, res) => {
    try {
        const { id } = req.params;
        
        console.log(`[API] 删除热点推荐 ID: ${id}`);
        
        // 检查热点推荐是否存在
        const [rows] = await db.execute('SELECT id FROM hot_stores WHERE id = ?', [id]);
        if (rows.length === 0) {
            return res.status(404).json({ message: '热点推荐不存在' });
        }
        
        // 删除数据
        await db.execute('DELETE FROM hot_stores WHERE id = ?', [id]);
        
        console.log(`[API] 热点推荐删除成功 ID: ${id}`);
        res.json({ message: '删除成功' });
    } catch (error) {
        console.error('[API] 删除热点推荐失败:', error);
        res.status(500).json({ message: '删除热点推荐失败' });
    }
};

module.exports = {
    getHotRecommends,
    getHotRecommendsAdmin,
    addHotRecommend,
    updateHotRecommend,
    deleteHotRecommend
}; 